package com.iwhalecloud.bss.kite.cucc.service.attr.handler;

import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.dto.attr.ChargeUnitDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.attr.ChargeUnitQryDTO;
import com.iwhalecloud.bss.kite.cucc.service.cache.ChargeUnitCache;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.service.attr.AttrData;
import com.iwhalecloud.bss.kite.service.attr.handler.AbstractAttrHandler;
import com.ztesoft.zsmart.core.exception.BaseAppException;
import com.ztesoft.zsmart.core.util.JsonUtil;
import org.apache.commons.collections.MapUtils;

import java.util.List;
import java.util.Map;

/**
 * @Classname ChargeUnitAttrHandler
 * @Description 收费单位
 * @Author zhang.song
 * @Date 2022-02-07 11:30
 */
public class ChargeUnitAttrHandler extends AbstractAttrHandler<KiteInst, AttrData> {

    @Override
    public String getValueDesc(KiteAttr attr, KiteInst inst, String value, AttrData data) {
        if(KiteStringUtils.isEmpty(value)) {
            return null;
        }
        if(KiteStringUtils.isJsonObject(value)) {
            Map<String, Object> dataMap = null;
            try {
                dataMap = JsonUtil.json2Object(value, Map.class);
            } catch (BaseAppException e) {
            }
            if(dataMap == null || dataMap.size() == 0) {
                return null;
            }
            return MapUtils.getString(dataMap, "chargeUnitName");
        }

        ChargeUnitQryDTO chargeUnitQryDTO = new ChargeUnitQryDTO();
        List<ChargeUnitDTO> chargeUnits = ChargeUnitCache.get(chargeUnitQryDTO);
        if(KiteListUtils.isNotEmpty(chargeUnits)) {
            String chargeUnitName = chargeUnits.stream().filter(chargeUnit -> KiteStringUtils.isEqual(chargeUnit.getId(), value)).findAny().map(ChargeUnitDTO::getName).orElse(null);
            return chargeUnitName;
        }
        return value;
    }
}
